<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
    <div id="root"></div>

    <script type="text/babel">
        /*
            useState修改值时重新渲染
            useRef修改值时不重新渲染
        */
        const { useState, useMemo, memo, useRef, useImperativeHandle, forwardRef } = React;

        const MyComponent = forwardRef((props, ref) => {
            // return <h2 ref={ref}> 子组件 </h2>
            /* useImperativeHandle 是 React 的一个 Hook，
                它用来在函数组件中暴露自定义的实例值给父组件。
                它常常与 forwardRef 一起使用，允许父组件访问子组件的特定功能或状态，
                而不需要直接暴露子组件的内部实现细节 
            */

            // useImperativeHandle 自定义 xxx.current 的值，让它变成 { function1, function2 }
            useImperativeHandle(ref, () => ({
                function1() {
                    console.log('子组件中的function1')
                },
                function2() {
                    console.log('子组件中的function2')
                }
            }))

            return <div ref={ref}>
                <h2 ref={ref}> 子组件 </h2>
                <h3> 哈哈</h3>
            </div>
        })

        function MyApp() {
            // const [count, setCount] = useState(0)
            // console.log('渲染了一次', count)
            // const handleclick = () => {
            //     setCount(count + 1)
            // }

            // const count = useRef()
            // console.log('渲染了一次', count.current)
            // const handleclick = () => {
            //     count.current + 1
            // }

            // const xxx = useRef(null)
            // const handleclick = () => {
            //     // console.dir(xxx.current)
            //     // xxx.current.innerHTML = "水哥澎湃"
            //     xxx.current.style.background = 'skyblue'
            // }

            // return <>
            //     <h1 ref={xxx} onClick={handleclick} > hello, world ! </h1>
            // </>

            // return <>
            //     <h1 ref={(xxxDom)=>{xxxDom.style.background='greenyellow'}} onClick={handleclick} > hello, world ! </h1>
            // </>

            const xxx = useRef(null)

            const handleclick = () => {
                console.dir(xxx.current)
                xxx.current.function1();
                xxx.current.function2();
            }

            return (
                <>
                    <h1 onClick={handleclick}> hello, world ! </h1>
                    <MyComponent ref={xxx} />
                </>
            )
        }

        const container = document.getElementById('root');
        const root = ReactDOM.createRoot(container);
        root.render(<MyApp />);

        console.log(root);

    </script>

</body>

</html>